package com.drondea.testclient;

import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.joran.JoranConfigurator;
import ch.qos.logback.core.joran.spi.JoranException;
import cn.hutool.core.io.resource.ClassPathResource;
import cn.hutool.cron.CronUtil;
import com.drondea.testclient.model.AppConfig;
import com.drondea.testclient.model.Model;
import com.drondea.testclient.panel.CmppPanel;
import com.drondea.testclient.panel.SgipPanel;
import com.drondea.testclient.panel.SmgpPanel;
import com.drondea.testclient.panel.SmppPanel;
import com.drondea.testclient.service.ConfigService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Options;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.LoggerFactory;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;

/**
 * 主窗口
 *
 * @author liuyanning
 */

@Slf4j
public class MainWindow {

    private JFrame frame;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        Options options = new Options();
        options.addOption("c", true, "config File Dir.default \"configuration\"");
        options.addOption("h", false, "print help");
        CommandLine line;
        try {
            line = new DefaultParser().parse(options, args);
            if (line.hasOption("h")) {
                HelpFormatter hf = new HelpFormatter();
                hf.printHelp("Options", options);
                return;
            }
            String configDir = line.getOptionValue("c");
            if (StringUtils.isNotBlank(configDir)) {
                File configDirFile = new File(configDir);
                ConfigService.CONFIG_PATH.set(configDirFile.getCanonicalPath() + File.separator);
            }
        } catch (Exception e) {
            log.error("", e);
        }

        initLogConfig();

        EventQueue.invokeLater(() -> {
            try {
                MainWindow window = new MainWindow();
                window.init();
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }

    /**
     * 窗口初始化
     */
    public void init() {
        Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();
        int width = (int) (dimension.width * 0.5), height = (int) (dimension.height * 0.5);
        frame = new JFrame("二进制科技SMS客户端工具");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setFont(new Font("Consolas", Font.PLAIN, 12));
        frame.setIconImage(new ImageIcon(new ClassPathResource("favicon.png").getUrl()).getImage());
        frame.setBounds(500, 210, width, height);

        ConfigService.loadAll();
        CronUtil.setMatchSecond(true);

        // 引用标签页
        CmppPanel cmppPanel = CmppPanel.getInstance();
        cmppPanel.init(width, height);
        SmgpPanel smgpPanel = SmgpPanel.getInstance();
        smgpPanel.init(width, height);
        SmppPanel smppPanel = SmppPanel.getInstance();
        smppPanel.init(width, height);
        SgipPanel sgipPanel = SgipPanel.getInstance();
        sgipPanel.init(width, height);

        Container contentPane = frame.getContentPane();
        JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP);
        tabbedPane.setBounds(0, 0, 720, 400);
        contentPane.add(tabbedPane, BorderLayout.CENTER);

        tabbedPane.addTab("CMPP20", cmppPanel.panel);
        tabbedPane.addTab("SMGP", smgpPanel.panel);
        tabbedPane.addTab("SMPP", smppPanel.panel);
        tabbedPane.addTab("SGIP", sgipPanel.panel);


        frame.setVisible(true);
        // 调节窗口大小监听
        frame.addComponentListener(new ComponentAdapter() {
            @Override
            public void componentResized(ComponentEvent e) {
                // 获取窗口宽度
                int widthTmp = frame.getWidth();
                // 获取窗口高度
                int heightTmp = frame.getHeight();
                tabbedPane.setFont(new Font(tabbedPane.getFont().getName(), tabbedPane.getFont().getStyle(), (int) (heightTmp * 0.04 * 0.6)));
                cmppPanel.initComponentBounds(widthTmp, heightTmp);
                smgpPanel.initComponentBounds(widthTmp, heightTmp);
                smppPanel.initComponentBounds(widthTmp, heightTmp);
                sgipPanel.initComponentBounds(widthTmp, heightTmp);
            }
        });
        // 窗口关闭监听
        frame.addWindowListener(new WindowAdapter() {

            @Override
            public void windowClosing(WindowEvent e) {
                //保存配置文件
                AppConfig appConfig = ConfigService.findBean(Model.APP_CONFIG.getCode(), "APP", AppConfig.class);
                ConfigService.update(Model.APP_CONFIG.getCode(), "APP", appConfig);
            }

        });
        CronUtil.start();
    }

    private static void initLogConfig() {
        File configPath = new File(ConfigService.CONFIG_PATH.get());
        if (!configPath.exists()) {
            try {
                boolean t = configPath.mkdirs();
                log.info("Create Config Path : {} {}", ConfigService.CONFIG_PATH.get(), t);
            } catch (Exception e) {
                log.error("", e);
            }
        }


        File logbackFile = new File(ConfigService.CONFIG_PATH.get() + "logback.xml");
        log.info("Config Path : {}", ConfigService.CONFIG_PATH.get());
        if (logbackFile.exists()) {
            LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
            JoranConfigurator configurator = new JoranConfigurator();
            configurator.setContext(lc);
            lc.reset();
            try {
                configurator.doConfigure(logbackFile);
            } catch (JoranException e) {
                e.printStackTrace(System.err);
                System.exit(-1);
            }
        }
    }
    
}
